package com.leyou.configs;

import com.leyou.pojo.CORSProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration    //声明这是一个配置类
@EnableConfigurationProperties(CORSProperties.class)
public class GlobalCORSConfig {

    @Bean   //将CorsFilter过滤器装配进springIOC容器中
    public CorsFilter corsFilter(CORSProperties corsProperties) {
        //1.创建CorsConfig配置信息
        CorsConfiguration config = new CorsConfiguration();
        //1.1.允许的域,不要写*,否则cookie就不能携带了
        corsProperties.getAllowedOrigin().forEach(config::addAllowedOrigin);
        //1.2.是否允许携带cookie
        config.setAllowCredentials(corsProperties.getAllowCredentials());
        //1.3.设置允许的方法
        corsProperties.getAllowedMethod().forEach(config::addAllowedMethod);
        //1.4.设置允许的头
        corsProperties.getAllowedHeader().forEach(config::addAllowedHeader);
        //1.5.设置有效时长
        config.setMaxAge(corsProperties.getMaxAge());

        //添加映射路径,我们拦截一切请求
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration(corsProperties.getFilterPath(), config);

        //返回新的CORSFilter过滤器
        return new CorsFilter(configurationSource);
    }
}
